package NetWork.Exercise005;

import java.io.*;
import java.net.Socket;
import java.util.UUID;

/**
 * ClassName:MyRunnable
 * Package:NetWork.Exercise005
 * Description:
 *
 * @Author:ZhangXin
 * @Create:2023/3/8-19:02
 * @Version:v1.0
 */
public class MyRunnable implements Runnable{
    Socket socket;
    public MyRunnable(Socket socket){
        this.socket=socket;
    }

    @Override
    public void run() {
        try {
            //读取数据并保存到本地文件中
            BufferedInputStream bis = new BufferedInputStream(socket.getInputStream());
            String name = UUID.randomUUID().toString().replace("-", "");
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("E:\\IDER\\IDEAWorkCode\\IDEADemo\\src\\NetWork\\Exercise003\\serverdir\\" + name + ".jpg"));

            int len;
            byte[] bytes = new byte[1024 * 1024];
            while ((len = bis.read(bytes)) != -1) {
                bos.write(bytes, 0, len);
            }

            //回写数据
            String str = "接收完毕";
            BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
            bw.write(str);
            bw.newLine();
            bw.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //释放资源
            if (socket!=null){
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }

    }
}
